﻿@using System.Configuration
@using System.Data.SqlClient
@{
    Layout = "~/_SiteLayout.cshtml";
    Page.Title = "Approve/Reject Claim";

    bool hasError = false;
    string errorMessage = string.Empty;
    bool hasSuccess = false;
    string successMessage = string.Empty;

    string frm_filter_entryowner = string.Empty;
    string frm_filter_claimdate = string.Empty;
    string frm_filter_entries = string.Empty;
    string sql_filter = string.Empty;

    List<KeppelLand.Entities.Claimant> claimantList = null;
    List<KeppelLand.Entities.Claim> claimList = null;
    KeppelLand.Entities.ClaimSummary claimSummary = null;

    if (IsPost)
    {
        if (Request.Form["actionButton"] == "filter")
        {
            frm_filter_entries = Request.Form["filter_entries"];
            string[] entries = frm_filter_entries.Split(',');
            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }
        } // if (Request.Form["actionButton"] == "filter")

        if (Request.Form["actionButton"] == "approve")
        {
            if (KeppelLand.Controllers.ClaimController.ApproveClaim(Request.Form["selected_id"]))
            {
                hasSuccess = true;
                successMessage = "Claim(s) are approved.";
            }
        } // if (Request.Form["actionButton"] == "approve")

        if (Request.Form["actionButton"] == "reject")
        {
            if (KeppelLand.Controllers.ClaimController.RejectClaims(KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(),
                Request.Form["rejection_reason"], Request.Form["selected_id"]))
            {
                using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EOCS"].ConnectionString))
                {
                    System.Data.DataSet dsRejectedClaims = new System.Data.DataSet("RejectedClaims");
                    System.Data.SqlClient.SqlCommand cmd = conn.CreateCommand();
                    System.Data.SqlClient.SqlDataAdapter da = new System.Data.SqlClient.SqlDataAdapter(cmd);
                    cmd.CommandText = @"SELECT * FROM Claim WHERE Id IN (SELECT data FROM dbo.fnSplitString(@IdList,','));";
                    cmd.Parameters.AddWithValue("@IdList", Request.Form["selected_id"]);

                    conn.Open();

                    da.Fill(dsRejectedClaims, "RejectedClaims");

                    cmd.CommandText = @"SELECT DISTINCT * FROM B2E WHERE EmployeeMaster IN (
        SELECT DISTINCT RecommenderId   FROM Claim WHERE Id IN (SELECT data FROM dbo.fnSplitString(@IdList,',')) 
UNION   SELECT DISTINCT ApproverId      FROM Claim WHERE Id IN (SELECT data FROM dbo.fnSplitString(@IdList,',')) 
) OR EmployeeMaster = @SupervisorId;";

                    cmd.Parameters.AddWithValue("@SupervisorId", 
                        KeppelLand.Helpers.TranslationHelper.GetEmployeeMasterByDomainName(KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName()));
                    da.Fill(dsRejectedClaims, "RecommenderAndApprover");

                    // TODO: Send rejection e-mail
                    string emailBody = KeppelLand.Controllers.ClaimController.RejectClaimEmailContent(
                        dsRejectedClaims.Tables["RejectedClaims"],
                        Request.Form["rejection_reason"],
                        KeppelLand.Helpers.TranslationHelper.GetNameLegalByDomainName(
                        KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName()));

                    foreach (System.Data.DataRow recipientRows in dsRejectedClaims.Tables["RecommenderAndApprover"].Rows)
                    {
                        KeppelLand.Helpers.EmailHelper.SendEmail(
                            recipientRows["Email"].ToString(), "Overtime claims rejection", emailBody, true);
                    }
                    
                    

                    hasSuccess = true;
                    successMessage = "Claim(s) are rejected.";
                }

            }
        } // if (Request.Form["actionButton"] == "reject")

        if (Request.Form["actionButton"] == "download")
        {
            frm_filter_entries = Request.Form["download_filter_entries"];
            string[] entries = frm_filter_entries.Split(',');
            if (entries.Length > 0)
            {
                frm_filter_entries = "[";
                foreach (string en in entries)
                {
                    frm_filter_entries = frm_filter_entries + "'" + en + "',";

                    if (!string.IsNullOrEmpty(en.Trim()))
                    {
                        sql_filter = sql_filter + string.Format("{0},", en.Trim());
                    }
                }
                frm_filter_entries = frm_filter_entries.Remove(frm_filter_entries.Length - 1, 1);
                frm_filter_entries = frm_filter_entries + "]";
                if (sql_filter.Length > 0)
                {
                    sql_filter = sql_filter.Remove(sql_filter.Length - 1, 1);
                }
            }
            
            byte[] fileBytes = KeppelLand.Controllers.ReportController.GetClaimsPendingApprovalReport(
                Request.Form["download_format"],
                KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(),
                sql_filter);
            Response.Clear();
            Response.ContentType = KeppelLand.Helpers.TranslationHelper.GetContentType(Request.Form["download_format"]);
            Response.AddHeader("content-disposition", "attachment; filename=" + KeppelLand.Helpers.TranslationHelper.GetFileName(Request.Form["download_format"], "Claims"));
            Response.BinaryWrite(fileBytes);
            Response.Flush();
            Response.End();
        } // if (Request.Form["actionButton"] == "download")
    } // if (IsPost)

    claimantList = KeppelLand.Controllers.ClaimController.GetClaimantListPendingRecommendationOrApproval(
        KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName());
    claimList = KeppelLand.Controllers.ClaimController.GetClaimListPendingRecommendationOrApproval(
        KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter);
    claimSummary = KeppelLand.Controllers.ClaimController.GetClaimSummaryPendingRecommendationOrApproval(
        KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName(), sql_filter);
}

@KeppelLand.Helpers.UserIdentityHelper.GetClaimantName()

@if (!KeppelLand.Helpers.UserIdentityHelper.IsTrainer())
{
    @RenderPage("~/Shared/Access_Control.cshtml");
    return;
}

<div class="container-fluid main-content" role="main">

    @RenderPage("~/Shared/Help_Tab.cshtml")

    @if (hasError)
    {
        <div class="alert alert-danger alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @Html.Raw(errorMessage)
        </div>
    }
    @if (hasSuccess)
    {
        <div class="alert alert-success alert-dismissible" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            @successMessage
        </div>
    }
    
    <h2>
        Approve/Reject Claim
        @if (KeppelLand.Helpers.UserIdentityHelper.IsSimulatingSupervisor())
        {
            <text>(simulating @DisplayHelper.LegalName(KeppelLand.Helpers.UserIdentityHelper.GetSupervisorName()))</text>
        }
        @if (KeppelLand.Helpers.UserIdentityHelper.IsTraining())
        {
            <text>(trainer account @KeppelLand.Helpers.UserIdentityHelper.GetTrainingSupervisorName())</text>
        }
    </h2>

    <form method="post" id="filter_form">

        <table class="table table-striped table-bordered">
            <tbody>
                <tr>
                    <th class="col-lg-2" style="vertical-align:middle;">
                        User Filter</th>
                    <td class="col-lg-10">
                        <select id="filter_entryowner">
                            <option value="">All</option>
                            @foreach (KeppelLand.Entities.Claimant claimant in claimantList)
                            {
                                <option value="@claimant.EmployeeMaster">@DisplayHelper.LegalNameByEmployeeMaster(claimant.EmployeeMaster)</option>
                            }
                        </select>
                    </td>
                </tr>
            </tbody>
        </table>

        <input type="hidden" name="filter_entries" id="filter_entries" />
        <input type="hidden" name="actionButton" id="filter_form_action" />
    </form>

    @RenderPage("~/Shared/Claims_Pending_RecommendationOrApproval.cshtml", claimList, claimSummary, true.ToString())

</div>

@RenderPage("~/Shared/Standard_Modals.cshtml")

<div class="modal fade" id="rejectionModal" tabindex="-1" role="dialog" aria-labelledby="rejectionModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="rejectionModalLabel">Reject Claim(s)</h4>
            </div>
            <div class="modal-body">

                <div class="panel panel-default">
                    <div class="panel-heading">
                        <h3 class="panel-title">Instructions</h3>
                    </div>
                    <div class="panel-body">
                        <ol>
                            <li>Enter your reasons for rejecting the claim(s).</li>
                            <li>Click Reject button to reject claims back to claimant.</li>
                            <li>Click Cancel button to close this dialog.</li>
                        </ol>
                    </div>
                </div>

                <label for="">Reason(s) for rejection of claims:</label>

                <textarea class="form-control" id="rejection_reason_entry" rows="12"></textarea>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="rejectionModal_OK">
                    <span class="glyphicon glyphicon-send" aria-hidden="true"></span> Reject
                </button>
                <button type="button" class="btn btn-primary" id="rejectionModal_Cancel" data-dismiss="modal">
                    <span class="glyphicon glyphicon-stop" aria-hidden="true"></span> Cancel
                </button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="helpModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="helpModalLabel">Help <small>(Approve Claim)</small></h4>
            </div>
            <div class="modal-body">
                <p>
                    Use this page to approve claims.
                </p>

                <div class="panel panel-default">
                    <div class="panel-heading">Instructions</div>
                    <div class="panel-body">
                        <p>
                            OK. How should this page work?<br />
                            This page should only be applicable to supervisors who have to approve/reject claims.<br />
                        </p>

                        <ul>
                            <li>Supervisors will review all claims that are submitted to them.</li>
                            <li>Supervisors will click on checkbox of respective rows for action (approve/reject).</li>
                            <li>After selection, supervisors will then click on approve/reject buttons.</li>
                            <li>System will give supervisors a dialog prompt whether to continue with their action.</li>
                            <li>Action will only be carry out, if user confirm action.</li>

                            <li>If there are no claims pending submission, page should indicate as such</li>
                        </ul>
                    </div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="helpModal_Close" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

@section Scripts
{
    <script type="text/javascript" src="~/Scripts/kendo/2014.3.1119/kendo.ui.core.min.js"></script>
    <script type="text/javascript" src="~/Scripts/moment.js"></script>
    <script type="text/javascript" src="~/Scripts/moment-with-locales.js"></script>
    <script type="text/javascript" src="~/Scripts/qTip/jquery.qtip.js"></script>
    <script type="text/javascript">
        function download(format) {
            $("#approval_form #actionButton").val("download");
            $("#approval_form #download_format").val(format);
            debugger;
            $("#download_filter_entries").val($("#filter_entryowner").data("kendoMultiSelect").value());
            $("#approval_form").submit();
        }

        (function ($) {
            "use strict";
            $(document).ready(function () {

                // Add tooltip to table
                $('#approvable_claims tbody td').qtip({
                    position: {
                        my: 'top center',  // Position my top left...
                        at: 'bottom center' // at the bottom right of...
                    }
                });

                //$("#filter_entryowner").kendoMultiSelect();
                var multi = $("#filter_entryowner").kendoMultiSelect({
                    change: function (e) {
                        $("#filter_entries").val(this.value());
                        $("#filter_form_action").val("filter");
                        $("#filter_form").submit();
                    }
                }).data("kendoMultiSelect");
                multi.value(@Html.Raw(frm_filter_entries));

                $("#checkbox_select_all").change(function () {
                    if (this.checked)
                        $(".checkbox_selected_id").prop("checked", true);
                    else
                        $(".checkbox_selected_id").prop("checked", false);
                });

                // User clicked reject
                $("#actionButton_reject").click(function () {
                    if ($(".checkbox_selected_id:checked").length > 0) {
                        $("#approval_form #actionButton").val(this.value);
                        $("#rejectionModal").modal('show');
                    }
                });
                $("#rejectionModal_OK").click(function () {
                    $("#approval_form #rejection_reason").val(
                        $("#rejectionModal #rejection_reason_entry").val());
                    $("#approval_form").submit();
                });

                // User clicked approve
                $("#actionButton_approve").click(function () {
                    if ($(".checkbox_selected_id:checked").length > 0) {
                        $("#approval_form #actionButton").val(this.value);
                        $('#confirmationModal').modal('show');
                    }
                });
                $("#confirmationModal_OK").click(function () {
                    $("#approval_form").submit();
                });

            });

        }(jQuery));

    </script>
}

@section Styles
{
    <link type="text/css" href="~/Scripts/qTip/jquery.qtip.css" rel="stylesheet" />
}